package cn.edu.ncut.cs.springboot.springbootdatabase.Controller;

import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Account;
import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Prisoner;
import cn.edu.ncut.cs.springboot.springbootdatabase.service.AccountService;
import cn.edu.ncut.cs.springboot.springbootdatabase.service.PrisonerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/prisoners")
public class PrisonerController {

    @Autowired
    private PrisonerService prisonerService;
    @Autowired
    private AccountService accountService;
    // 获取所有囚犯信息
    @GetMapping("/list")
    public List<Prisoner> listUser() {
        return prisonerService.findAll();
    }

    // 根据ID获取单个囚犯信息
    @GetMapping("/{id}")
    public Optional<Prisoner> findById(@PathVariable("id") Integer id){
        return prisonerService.findById(id);
    }

    // 新增囚犯信息
    @PostMapping("/add")
    public String add(@RequestBody() Prisoner prisoner){
        try {
            // 保存Prisoner信息到prisoner表
            prisoner.encodePassword();
            prisonerService.savePrisoner(prisoner);
            Account account = new Account();
            account.setRegisterTime(LocalDateTime.now());
            account.setRole("Prison");
            account.setId((prisoner.getId()));
            account.setUsername(prisoner.getName());
            account.setPassword(prisoner.getPassword());
            account.encodePassword();
            // 保存Account信息到account表
            accountService.saveAccount(account);
            return String.valueOf(new ResponseEntity<>("success!", HttpStatus.OK));
        } catch (Exception e) {
            return String.valueOf(new ResponseEntity<>("添加过程出现异常，请检查输入数据及相关配置", HttpStatus.INTERNAL_SERVER_ERROR));
        }
    }

    // 删除囚犯信息
    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") Integer id){
        Optional<Prisoner> prisoner = prisonerService.findById(id);
        if (prisoner.isPresent()) {
            // 获取prisoner的name并调用accountService的新方法删除对应的Account对象
            accountService.deleteUsername(prisoner.get().getName());
            prisonerService.deletePrisoner(id);
            return "success!";
        }
        return "未找到对应的囚犯信息，删除失败";
    }
}